from appium import webdriver
import time
import random
import threading
import os
import socket
import json


# 建立连接
def dz_xiaomi():
    print('小米手机开始调试')
    desired_caps = {}
    desired_caps['platformName'] = 'Android'
    desired_caps['platformVersion'] = '8.1.0'
    desired_caps['deviceName'] = 'b5c39bec0604'
    desired_caps['noReset'] = True  # 不重新签名apk
    desired_caps['noSign'] = True  # 不重新签名apk
    # desired_caps['deviceName'] = '192.168.0.124:8888'
    # com.ss.android.ugc.aweme /.detail.ui.LiveDetailActivity
    # desired_caps['appPackage'] = 'com.lbe.security.miui'
    # desired_caps['appActivity'] = 'com.android.packageinstaller.permission.ui.GrantPermissionsActivity'
    desired_caps['appPackage'] = 'com.ss.android.ugc.aweme'
    desired_caps['appActivity'] = '.splash.SplashActivity'
    driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
    driver.implicitly_wait(10)
    print('创建链接完成，开始操作手机')


# 截图
def take_screenShot(driver,name = "takeShot"):
    day = time.strftime("%Y-%m-%d", time.localtime(time.time()))
    fq = "..\\screenShots\\"+day
    tm = time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime(time.time()))
    type = '.png'
    filename = ""
    if os.path.exists(fq):
        filename = fq + "\\" + name + type
    else:
        os.makedirs(fq)
        filename = fq + "\\" +  name + type
    print('开始获取屏幕截图操作')
    driver.get_screenshot_as_file(filename)
    return driver

# 请求
def start_service(driver) :
    server = socket.socket()
    host = socket.gethostname()
    port = 12345
    server.bind((host, port))
    server.listen(5)
    print('请求服务开始')
    while True:
        conn,addr = server.accept() #等待链接,多个链接的时候就会出现问题,其实返回了两个值
        data = conn.recv(1024)  # 接收数据
        b = data.decode();
        b = json.loads(str(b));
        print('recive:'+ str(b))  # 打印接收到的数据
        if (b['type'] == 1):
            opt_dz(driver, b['aweme_id'], b['id'])
        if (b['type'] == 2):
            opt_gz(driver, b['anchor_id'], b['id'])
        msg = '1'
        conn.send(msg.encode('utf-8'))
        conn.close()


# 操作
#    点赞
def opt_dz(driver,id, task) :
    scheme_url = "snssdk1128://aweme/detail/" +id;  # 跳转到具体的视频页面
    driver.get(scheme_url)
    time.sleep(3)
    if driver.find_element_by_id("com.ss.android.ugc.aweme:id/al8").click():
        pass
    print('点赞按钮并等待10s')
    time.sleep(10)
    take_screenShot(driver, task)
    print('完成任务')
    driver.get(scheme_url)

#   关注
def opt_gz(driver,id, task) :
    scheme_url = "snssdk1128://user/profile/" +id;  # 跳转到具体的视频页面
    driver.get(scheme_url)
    driver.find_element_by_id("com.ss.android.ugc.aweme:id/ds0").click()
    print('点击关注按钮并等待10s')
    time.sleep(10)
    take_screenShot(driver,task)
    print('完成任务')

if __name__ == '__main__':
    driver = dz_xiaomi()
    start_service(driver)